package org.jeecg.modules.wmhb.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 技改单
 * @Author: jeecg-boot
 * @Date: 2024-08-31
 * @Version: V1.0
 */
@Api(tags = "技改单")
@RestController
@RequestMapping("/wmhb/wmSkillChange")
@Slf4j
public class WmSkillChangeController extends JeecgController<WmSkillChange, IWmSkillChangeService> {
    @Autowired
    private IWmSkillChangeService wmSkillChangeService;
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmTaskbookService wmTaskbookService;
	@Autowired
	private IWmFlowDeptService wmFlowDeptService;
	@Autowired
	private IWmTaskbookFlowService wmTaskbookFlowService;
	@Autowired
	private IWmTaskFlowService wmTaskFlowService;

    /**
     * 分页列表查询
     *
     * @param wmSkillChange
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "技改单-分页列表查询")
    @ApiOperation(value = "技改单-分页列表查询", notes = "技改单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmSkillChange>> queryPageList(WmSkillChange wmSkillChange,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<WmSkillChange> queryWrapper = QueryGenerator.initQueryWrapper(wmSkillChange, req.getParameterMap());
        Page<WmSkillChange> page = new Page<WmSkillChange>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        IPage<WmSkillChange> pageList = wmSkillChangeService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmSkillChange
     * @return
     */
    @AutoLog(value = "技改单-添加")
    @ApiOperation(value = "技改单-添加", notes = "技改单-添加")
    @RequiresPermissions("wmhb:wm_skill_change:add")
    @RequestMapping(value = "/add", method = {RequestMethod.PUT,RequestMethod.POST})
    @Transactional
    public Result<String> add(@RequestBody WmSkillChange wmSkillChange) {
        wmSkillChangeService.save(wmSkillChange);
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmSkillChange.getWmTaskbookId());
        wmTaskbook.setStatus(UserConstant.TASK_STATUS_SKILL_CHANGE);
        wmTaskbookService.updateById(wmTaskbook);
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmSkillChange.getWmTaskbookId(), wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        for (WmTask wmTask : wmTaskList) {
            wmTask.setStatus(UserConstant.TASK_STATUS_SKILL_CHANGE);
            wmTaskService.updateById(wmTask);
        }

        //回到上一流程
        prevFlowTaskbook(wmTaskbook);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmSkillChange
     * @return
     */
    @AutoLog(value = "技改单-编辑")
    @ApiOperation(value = "技改单-编辑", notes = "技改单-编辑")
    @RequiresPermissions("wmhb:wm_skill_change:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmSkillChange wmSkillChange) {
        wmSkillChangeService.updateById(wmSkillChange);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "技改单-通过id删除")
    @ApiOperation(value = "技改单-通过id删除", notes = "技改单-通过id删除")
    @RequiresPermissions("wmhb:wm_skill_change:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        wmSkillChangeService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "技改单-批量删除")
    @ApiOperation(value = "技改单-批量删除", notes = "技改单-批量删除")
    @RequiresPermissions("wmhb:wm_skill_change:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmSkillChangeService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "技改单-通过id查询")
    @ApiOperation(value = "技改单-通过id查询", notes = "技改单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmSkillChange> queryById(@RequestParam(name = "id", required = true) String id) {
        WmSkillChange wmSkillChange = wmSkillChangeService.getById(id);
        if (wmSkillChange == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmSkillChange);
    }

    /**
     * 任务书下一流程
     *
     * @param wmTaskbook
     * @return
     */
    private void nextFlowTaskbook(WmTaskbook wmTaskbook) {
        //根据流程ID查找流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
        Integer nextIndex = wmTaskbook.getCurrentNodeIndex() + 1;
        if (nextIndex >= wmFlowDeptList.size()) {
            throw new RuntimeException("请补充完整的流程定义");
        }
        wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
        wmTaskbook.setCurrentNodeIndex(nextIndex);
        wmTaskbookService.updateById(wmTaskbook);

        nextFlowTask(wmTaskbook);
    }

    /**
     * 任务书上一流程
     *
     * @param wmTaskbook
     * @return
     */
    private void prevFlowTaskbook(WmTaskbook wmTaskbook) {
        //根据流程ID查找流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
        Integer prevIndex = wmTaskbook.getCurrentNodeIndex() - 1;
        if (prevIndex < 0) {
            throw new RuntimeException("流程异常");
        }
        wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
        wmTaskbook.setCurrentNodeIndex(prevIndex);
        wmTaskbookService.updateById(wmTaskbook);

        prevFlowTask(wmTaskbook);
    }

    /**
     * 任务下一流程(任务书下所有任务都更新)
     *
     * @param wmTaskbook
     * @return
     */
    private void nextFlowTask(WmTaskbook wmTaskbook) {
        //更新任务书下所有任务到下一个流程
        LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmTask::getCurrentNodeId, wmTaskbook.getCurrentNodeId());
		updateWrapper.set(WmTask::getCurrentNodeIndex, wmTaskbook.getCurrentNodeIndex());
		updateWrapper.set(WmTask::getCurrentNodeTime, new Date());
		if (wmTaskbook.getCurrentVersion() == null) {
			updateWrapper.isNull(WmTask::getCurrentVersion);
		}
		else {
			updateWrapper.eq(WmTask::getCurrentVersion, wmTaskbook.getCurrentVersion());
		}
		updateWrapper.eq(WmTask::getWmTaskbookId, wmTaskbook.getId());
        wmTaskService.update(null, updateWrapper);

        //获取任务书下所有任务
        Integer currIndex = wmTaskbook.getCurrentNodeIndex(); //当前索引已经是下一流程
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskbook.getId(), wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        for (WmTask wmTask : wmTaskList) {
            //设置上一流程实际结束时间和当前流程实际开始时间
            WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), currIndex - 1);
            WmTaskFlow wmTaskFlowNext = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), currIndex);
            wmTaskFlowCurr.setFactEndTime(new Date());
            wmTaskFlowNext.setFactBeginTime(new Date());
            wmTaskFlowService.updateById(wmTaskFlowCurr);
            wmTaskFlowService.updateById(wmTaskFlowNext);
        }
    }

    /**
     * 任务上一流程
     *
     * @param wmTaskbook
     * @return
     */
    private void prevFlowTask(WmTaskbook wmTaskbook) {
        //更新任务书下所有任务到上一个流程
        LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmTask::getCurrentNodeId, wmTaskbook.getCurrentNodeId());
		updateWrapper.set(WmTask::getCurrentNodeIndex, wmTaskbook.getCurrentNodeIndex());
		updateWrapper.set(WmTask::getCurrentNodeTime, new Date());
		if (wmTaskbook.getCurrentVersion() == null) {
			updateWrapper.isNull(WmTask::getCurrentVersion);
		}
		else {
			updateWrapper.eq(WmTask::getCurrentVersion, wmTaskbook.getCurrentVersion());
		}
		updateWrapper.eq(WmTask::getWmTaskbookId, wmTaskbook.getId());
        wmTaskService.update(null, updateWrapper);

        //获取任务书下所有任务
        Integer currIndex = wmTaskbook.getCurrentNodeIndex();//当前索引已经是上一流程
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskbook.getId(), wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        for (WmTask wmTask : wmTaskList) {
            //设置上一流程实际结束时间和当前流程实际开始时间
            WmTaskFlow wmTaskFlowPrev = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), currIndex);
            WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), currIndex + 1);
            wmTaskFlowPrev.setFactEndTime(null);
            wmTaskFlowCurr.setFactBeginTime(null);
            wmTaskFlowService.updateById(wmTaskFlowPrev);
            wmTaskFlowService.updateById(wmTaskFlowCurr);
        }
    }

}
